#!/usr/bin/env python3
import os
import shutil
import natsort

from os.path import join
from argparse import ArgumentParser

mapping = (
    1, 16,
    15, 2,

    3, 14,
    13, 4,

    5, 12,
    11, 6,

    7, 10,
    9, 8,
)


def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--indir', type=str, required=True,
                        help='Input directory')
    parser.add_argument('--outdir', type=str, required=True,
                        help='Output directory')
    args = parser.parse_args()

    if not os.path.exists(args.outdir):
        os.mkdir(args.outdir)

    files = os.listdir(args.indir)
    files = natsort.natsorted(files)

    offset = 0

    for pages in chunks(files, 16):
        if len(pages) == 16:
            for i in range(16):
                file = pages[i]
                n = mapping[i]

                new_name = str(offset + n) + '.pdf'
                shutil.copyfile(
                    join(args.indir, file),
                    join(args.outdir, new_name)
                )

                print(f'{file} => {new_name}')
            offset += 16
        else:
            break
